import { deepCopy, messages, queryCurrencyPrecision, uniquelizeArray } from "share/common";
import React from "react";
import { connect } from "react-redux";
import { Form, Select, Row, Col, Affix, Button, message, Checkbox } from "antd";
const FormItem = Form.Item;
const Option = Select.Option;

import "styles/expense-reimbursement-control/reimbursement/new-standard.scss";
import Chooser from "components/chooser";
import reimburseService from "containers/expense-reimbursement-control/expense-standard/reimbursement/reimbursement.service";
import errorMessage from "share/errorMessage";
import selectorData from "share/selectorData";

class NewStandard extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      precision: 2,
      info: props.params.info || {},
      cityPlaceholder: messages("expense-8.key9") /*通用*/,
      userPlaceholder: messages("expense-8.key9") /*通用*/,
    };
  }

  typeCode = {
    PLANE_CABIN: messages("expense-8.key452") /*飞机舱等*/,
    TRAIN_SEAT_CLASS: messages("expense-8.key453") /*火车座等*/,
    SHIP_CABIN: messages("expense-8.key454") /*轮船座次*/,
  };

  componentDidMount() {
    const { company, info, ruleInfo } = this.props;
    this.setState({
      precision: queryCurrencyPrecision(info.currencyCode || ruleInfo.baseCurrencyCode || company.baseCurrency),
    });
  }

  handleSave = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { ruleOID, info, isCopy, customEnumerationList } = this.props.params;
        values.ruleOID = ruleOID;
        let customEnumerationItems = (values.customEnumerationItems || []).map((i) => {
          return customEnumerationList.filter((c) => c.value === i)[0];
        });
        values.customEnumerationItems = deepCopy(customEnumerationItems).filter((i) => !!i);
        !isCopy && (values.standardOID = info.standardOID);
        this.setState({ loading: true });
        reimburseService
          .newOrEditStandard(values)
          .then(() => {
            this.setState({ loading: false });
            this.props.close(true);
            message.success(messages("common.save.success", { arg1: "" }) /*{arg1} 保存成功*/);
          })
          .catch((e) => {
            errorMessage(e.response);
            this.setState({ loading: false });
          });
      }
    });
  };

  onCancel = () => {
    this.props.close();
  };

  //修改关联类型
  handleAssociateTypeChange = (type, value) => {
    const { setFields, getFieldValue } = this.props.form;
    if (type === "city") {
      setFields({ citys: { value: getFieldValue("citys"), errors: null } });
      this.setState({
        cityPlaceholder: value ? messages("expense-8.key9") /*通用*/ : messages("common.select") /*请选择*/,
      });
    }
    if (type === "user") {
      setFields({
        userGroups: { value: getFieldValue("userGroups"), errors: null },
      });
      this.setState({
        userPlaceholder: value ? messages("expense-8.key9") /*通用*/ : messages("common.select") /*请选择*/,
      });
    }
  };

  //渲染关联类型
  renderAssociateType = (type) => {
    return (
      <Select
        onChange={(value) => this.handleAssociateTypeChange(type, value)}
        getPopupContainer={(triggerNode) => triggerNode.parentNode}
      >
        <Option value={1}>{messages("expense-8.key72") /*包含*/}</Option>
        <Option value={0}>{messages("expense-8.key73") /*不包含*/}</Option>
      </Select>
    );
  };

  render() {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { ruleInfo, customEnumerationList } = this.props;
    const { loading, info, userPlaceholder } = this.state;

    let selectorItem = selectorData["city_level_org"];
    selectorItem.key = "levelOID";

    return (
      <div className="new-form">
        <Form onSubmit={this.handleSave}>
          <FormItem label={messages("expense-8.key11") /*适用人员*/}>
            <Row gutter={12}>
              <Col span={8}>
                {getFieldDecorator("userAssociateType", {
                  rules: [
                    {
                      required: getFieldValue("userAssociateType") === 0,
                      message: messages("common.select") /*请选择*/,
                    },
                  ],
                  initialValue: info.userAssociateType || info.userAssociateType === 0 ? info.userAssociateType : 1,
                })(this.renderAssociateType("user"))}
              </Col>
              <Col span={15}>
                {getFieldDecorator("userGroups", {
                  rules: [
                    {
                      required: getFieldValue("userAssociateType") === 0,
                      message: messages("common.select") /*请选择*/,
                    },
                  ],
                  initialValue: info.userGroups,
                })(
                  <Chooser
                    type="user_group"
                    valueKey="userGroupOID"
                    labelKey="name"
                    newline
                    placeholder={userPlaceholder}
                    listExtraParams={{
                      levelCode: ruleInfo.levelCode,
                      levelOrgId: ruleInfo.levelOrgId,
                    }}
                  />
                )}
              </Col>
            </Row>
          </FormItem>
          <FormItem label={this.typeCode[info.nonAmountCtrlItem]}>
            {getFieldDecorator("customEnumerationItems", {
              rules: [
                {
                  required: true,
                  message: messages("common.select") /*请选择*/,
                },
              ],
              initialValue: (info.customEnumerationItems || []).map((i) => i.value),
            })(
              <Checkbox.Group
                options={uniquelizeArray(customEnumerationList.concat(info.customEnumerationItems || []), "value").map(
                  (i) => {
                    return { label: i.messageKey, value: i.value };
                  }
                )}
              />
            )}
          </FormItem>
          <Affix offsetBottom={0} className="slide-footer">
            <Button type="primary" htmlType="submit" loading={loading}>
              {messages("common.save") /*保存*/}
            </Button>
            <Button onClick={this.onCancel} className="btn-cancel">
              {messages("common.cancel") /*取消*/}
            </Button>
          </Affix>
        </Form>
      </div>
    );
  }
}

NewStandard.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    tenantMode: state.main.tenantMode,
    languageList: state.login.languageList,
    language: state.main.language,
    user: state.login.user,
  };
}

const WrappedNewStandard = Form.create()(NewStandard);

export default connect(mapStateToProps)(WrappedNewStandard);
